//=============================================================================
// VIPArcher_Character_Animations.js
//=============================================================================
/*:
 * @plugindesc 行走圖動畫擴展，八方向|奔跑|待機|多幀
 * @author VIPArcher (edited by 老饕)
 *
 * @param Dir8_Flag
 * @desc 素材使用該腳本的標誌
 * @default %
 *
 * @param Frames_Flag
 * @desc 設定幀數的標誌
 * @default #
 *
 * @help 使用該腳本的行走圖素材文件名前面添加一個標誌：默認為 %
 * 文件名的名為規範(默認設定)如下：
 * %VIPArcher.png , 素材為2*4的標誌素材
 * 第一行：第一個格子是四方向，第二個格子是四方向奔跑，第三個是四方向待機；
 * 第二行：第一個格子是八方向，第二個格子是八方向奔跑，第三個是八方向待機；
 *
 * 使用多幀則名為(默認設定): 文件名#幀數,默認幀.png
 * 例如 %VIPArcher#6,3.png
 */
(function() {

    var parameters = PluginManager.parameters('SWDA_VIPArcher_Character_Animations');
    var dir8_flag  = String(parameters['Dir8_Flag']   || '%');	// 八方向標誌
    var frame_flag = String(parameters['Frames_Flag'] || '#');	// 幀數標誌
	
	
	
//=============================================================================
// ImageManager
//=============================================================================
	
	// 判斷是否是八方向行走圖
    ImageManager.isDir8Character = function(filename) {	
        var reg = new RegExp("^\[\\!\\$\\" + dir8_flag + ']+');
        var sign = filename.match(reg);
        return sign && sign[0].contains(dir8_flag);
    };
	
//=============================================================================
// Game_CharacterBase
//=============================================================================

	// 補充initMembers（刪掉了站立等待部分）
    var _Game_CharacterBaseinitMembers = Game_CharacterBase.prototype.initMembers;
    Game_CharacterBase.prototype.initMembers = function() {
        _Game_CharacterBaseinitMembers.call(this);
        this._isDir8Character = false;
    };
	
	// 如果是八方向行走圖補充對應變量賦值（修正指定行走圖index無效問題）
    var _Game_CharacterBasesetImage = Game_CharacterBase.prototype.setImage;
    Game_CharacterBase.prototype.setImage = function(characterName, characterIndex) {
        _Game_CharacterBasesetImage.call(this, characterName, characterIndex);
        this.getCharacterMaxFrame(characterName);
        if (ImageManager.isDir8Character(characterName)) {
            this._characterIndex  = characterIndex;	//修正指定行走圖index無效問題。
            this._isDir8Character = true;
        };
    };
	
	// 斜向移動
    var _Game_CharacterBasemoveDiagonally = Game_CharacterBase.prototype.moveDiagonally;
    Game_CharacterBase.prototype.moveDiagonally = function(horz, vert) {
        _Game_CharacterBasemoveDiagonally.call(this, horz, vert);
        if (horz > 5) {
            vert > 5 ? this.setDirection(9) : this.setDirection(3);
        } else {
            vert > 5 ? this.setDirection(7) : this.setDirection(1);
        };
    };
	// 獲取幀數，若存在幀數標誌則第一位是maxFrame，第二位是formerpattern。若不存在，則默認。
    Game_CharacterBase.prototype.getCharacterMaxFrame = function(characterName) {
        var framedate = characterName.match(new RegExp(frame_flag + "(\\d+)-(\\d+)"));
		//alert(framedate)
        if (framedate) {
            this._maxFrame = parseInt(framedate[1]);
            this._formerPattern = parseInt(framedate[2]);
        } else{
            this._maxFrame = 4;
            this._formerPattern = 0;
        };
    };
	
    Game_CharacterBase.prototype.pattern = function() {
        return this._pattern < this.maxFrame() ? this._pattern : 1;
    };
    Game_CharacterBase.prototype.maxFrame = function() {
        return this._maxFrame;
    };
    Game_CharacterBase.prototype.maxPattern = function() {
        if (this._maxFrame === 3) {
            return 4;
        } else {
            return this._maxFrame;
        };
    };
    Game_CharacterBase.prototype.isOriginalPattern = function() {
        return this.pattern() === this._formerPattern;
    };
    Game_CharacterBase.prototype.resetPattern = function() {
        this.setPattern(this._formerPattern);
    };
	
    Game_CharacterBase.prototype.setCharacterIndex = function(index) {
		this._characterIndex = index;
    };
	// SWDA：修正切換選單時行走圖默認為第1幀，而非第_formerPattern幀的bug
	Game_CharacterBase.prototype.straighten = function() {
    if (this.hasWalkAnime() || this.hasStepAnime()) {
        this._pattern = this._formerPattern;
    }
		this._animationCount = 0;
	};
	
	Game_CharacterBase.prototype.animationWait = function() {
		return (9 - this.realMoveSpeed()) * 3 * 4/this.maxFrame();
	};
	Game_CharacterBase.prototype.realMoveSpeed = function() {
    return this._moveSpeed + (this.isDashing() ? 1 : 0);
};
	
//=============================================================================
// Game_Player
//=============================================================================

    Game_Player.prototype.moveByInput = function() {
        if (!this.isMoving() && this.canMove()) {
            var direction = Input.dir8;
            if (direction > 0) {
                $gameTemp.clearDestination();
            } else if ($gameTemp.isDestinationValid()){
                var x = $gameTemp.destinationX();
                var y = $gameTemp.destinationY();
                direction = this.findDirectionTo(x, y);
            }
            if (direction > 0) {
                if (direction % 2 == 0){
                    this.moveStraight(direction);
                    return;
                }
                if (direction < 5){
                    this.moveDiagonally(direction + 3 , 2);
                } else {
                    this.moveDiagonally(direction - 3 , 8);
                }
            }
        }
    };


    var _Game_PlayermoveDiagonally = Game_Player.prototype.moveDiagonally;
    Game_Player.prototype.moveDiagonally = function(horz, vert) {
        if (!this.canPass(this._x, this._y, horz) && !this.canPass(this._x, this._y, vert)){
            this.setMovementSuccess(false);
            return;
        }
        if (this.canPass(this._x, this._y, horz) && !this.canPass(this._x, this._y, vert)){
            this.moveStraight(horz);
            return;
        }
        if (this.canPass(this._x, this._y, vert) && !this.canPass(this._x, this._y, horz)){
            this.moveStraight(vert);
            return;
        }
        if (!this.canPassDiagonally(this._x, this._y, horz, vert)) {
            if (Math.random() > 0.5){
                this.setDirection(vert); this.moveStraight(vert);
            } else {
                this.setDirection(horz); this.moveStraight(horz);
            }
            return;
        }
        _Game_PlayermoveDiagonally.call(this, horz, vert);
    };
	
//=============================================================================
// Game_Event（事件頁設定，修正事件頁指定的行走圖斜向失效問題）
//=============================================================================
	Game_Event.prototype.setupPageSettings = function() {
		var page = this.page();
		var image = page.image;
		if (image.tileId > 0) {
			this.setTileImage(image.tileId);
		} else {
			this.setImage(image.characterName, image.characterIndex);
		}
		
		// 修正事件頁指定的行走圖斜向失效問題
		if (this._originalDirection !== image.direction) {
			this._originalDirection = image.direction;
			this._prelockDirection = 0;
			this.setDirectionFix(false);
			if (this._isDir8Character && this._characterIndex>=4){
				if (image.direction < 5){
					this.setDirection(image.direction-1);
				} else {
					this.setDirection(image.direction+1);
				}
			}else{
				this.setDirection(image.direction);
			}
		// 斜向directgion不變，但實際方向改變
		} else if (this._isDir8Character && this._characterIndex>=4) {
			if (image.direction < 5){
				this.setDirection(image.direction-1);
			} else {
				this.setDirection(image.direction+1);
			}
		}
		// 修正事件頁指定的行走圖斜向失效問題
		
		if (this._originalPattern !== image.pattern) {
			this._originalPattern = image.pattern;
			this.setPattern(image.pattern);
		}
		this.setMoveSpeed(page.moveSpeed);
		this.setMoveFrequency(page.moveFrequency);
		this.setPriorityType(page.priorityType);
		this.setWalkAnime(page.walkAnime);
		this.setStepAnime(page.stepAnime);
		this.setDirectionFix(page.directionFix);
		this.setThrough(page.through);
		this.setMoveRoute(page.moveRoute);
		this._moveType = page.moveType;
		this._trigger = page.trigger;
		if (this._trigger === 4) {
			this._interpreter = new Game_Interpreter();
		} else {
			this._interpreter = null;
		}
	};
//=============================================================================
// Sprite_Character（行走圖分塊劃分等設定）
//=============================================================================

	//行走圖劃分（方向）SWDA：修正無待機行走圖的劃分、修正指定行走圖index無效問題。
    Sprite_Character.prototype.characterPatternY = function() {
		// 正4方向
        if (this._character.direction() % 2 == 0){
            if (this._character._isDir8Character){
				this._character.setCharacterIndex(this._character.characterIndex() % 4);
            };
            return (this._character.direction() - 2) / 2;
        } else {
		// 斜4方向
			// 八方向角色用斜四方向位置的圖
            if (this._character._isDir8Character){
				this._character.setCharacterIndex(4 + this._character.characterIndex() % 4);
				return parseInt((this._character.direction() + 1) / 3);
			}
			// 四方向角色：用正四方向位置的圖代替
			else {
				switch (this._character.direction()) {
				case 1:
					return 1;
				case 3:
					return 2;
				case 7:
					return 3;
				case 9:
					return 3;
				}
            };
        }
    };

	
	// SWDA：行走圖分塊數（默認4，八方向為1（待機和行走）
    Game_CharacterBase.prototype.maxBlockX = function() {
        if (this._isDir8Character) {
            return 1;
        } else {
            return 1;
        };
    };

	//分塊寬度
    Sprite_Character.prototype.patternWidth = function() {
        if (this._tileId > 0) {
            return $gameMap.tileWidth();
        } else if (this._isBigCharacter) {
            return this.bitmap.width / this._character.maxFrame();
        } else {
            return this.bitmap.width / (this._character.maxFrame() * this._character.maxBlockX());	//SWDA：八方向分塊減少
        }
    };
	
	//分塊高度
	Sprite_Character.prototype.patternHeight = function() {
		if (this._tileId > 0) {
			return $gameMap.tileHeight();
		} else if (this._isBigCharacter) {
			return this.bitmap.height / 4;
		} else if (this._character._isDir8Character){
			return this.bitmap.height / 8;
		} else {
			return this.bitmap.height / 4;
		}
	};
		
	// X軸分塊
    Sprite_Character.prototype.characterBlockX = function() {
        if (this._isBigCharacter) {
            return 0;
        } else {
            var index = this._character.characterIndex();
			return index % 4 * 3;
            //return (index % 4) * this._character.maxFrame();
        }
    };
	
	// 補充：草叢深度
	Game_CharacterBase.prototype.refreshBushDepth = function() {
    if (this.isNormalPriority() && !this.isObjectCharacter() &&
            this.isOnBush() && !this.isJumping()) {
        if (!this.isMoving()) {
            this._bushDepth = 30;
        }
    } else {
        this._bushDepth = 0;
    }
};
//=============================================================================
// Game_Character（補充：八方向設定行走路線相關）
//=============================================================================
	//set 8dir random move
	Game_Character.prototype.moveRandom = function() {
		
		var d = 1 + Math.randomInt(8);
		if (d % 2 == 0)
		{
			if (this.canPass(this.x, this.y, d)) {
				this.moveStraight(d);
				
			}
		}
		else {
			var horz = 4;
			var vert = 2;
			switch (d) {
				case 1: horz = 4; vert = 2;
				case 3: horz = 6; vert = 2;
				case 7: horz = 4; vert = 8;
				case 9: horz = 6; vert = 8;
			}
			
			if (this.canPassDiagonally(this.x, this.y, horz, vert))
			{
				this.moveDiagonally(horz, vert);
			}
		}
		
	};

	// SWDA：set 8dir moveForward
	Game_Character.prototype.moveForward = function() {

		if (this.direction() % 2 == 0){
			this.moveStraight(this.direction());
		}
		else{
			var horz = 4;
			var vert = 2;
			switch (this.direction()) {
				case 1: horz = 4; vert = 2;
				case 3: horz = 6; vert = 2;
				case 7: horz = 4; vert = 8;
				case 9: horz = 6; vert = 8;
			}
			this.moveDiagonally(horz, vert);
		}
			
	};
	
	// SWDA：行走圖繪製（存檔界面）
Window_Base.prototype.drawCharacter = function(characterName, characterIndex, x, y) {
    var bitmap = ImageManager.loadCharacter(characterName);
    var big = ImageManager.isBigCharacter(characterName);
	var dir8 = ImageManager.isDir8Character(characterName);
	
	var framedata = characterName.match(new RegExp(frame_flag + "(\\d+)-(\\d+)"));
	if (framedata) {
        var maxFrame = parseInt(framedata[1]);
    } else{
        var maxFrame = 4;
    };
	
	
    var pw = bitmap.width / (big ? 3 : maxFrame);
    var ph = bitmap.height / (big ? 4 : dir8? 8 : 4);
    this.contents.blt(bitmap, 0, 0, pw, ph, x - pw / 2, y - ph);
};
})();



